package com.ciwong.epaper.modules.epaper.dao;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.DeleteEP;
import com.ciwong.epaper.modules.epaper.bean.LearnRecord;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.VideoExplainWorkAnswers;
import com.ciwong.epaper.modules.epaper.util.UnicodeReader;
import com.ciwong.epaper.modules.evaluate.bean.DKAnswer;
import com.ciwong.epaper.modules.evaluate.bean.EssayAnswer;
import com.ciwong.epaper.modules.evaluate.bean.SubmitResult;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.dao.db.db.StudyRecordDB;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.UploadFileHelper;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerSubMitResultBean;
import com.ciwong.epaper.modules.scan.bean.QRCodeInfo;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ZipHelper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 电子报 相关业务Dao
 *
 * @author bin
 * @version ciwong v.1.0 2015/7/23 20:09
 * @since ciwong v.1.0
 */
public class EpaperDao {
    private static EpaperDao instance;

    private Handler mHandler;
    private static Context mContext;

    private EpaperDao() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * 获取唯一实例
     *
     * @return 唯一实例
     */
    public static EpaperDao getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    /**
     * 实例化对象
     */
    private static synchronized void syncInit() {
        if (instance == null) {
            instance = new EpaperDao();
        }
    }

    /**
     * 设置上下文对象
     *
     * @param context 上下文对象
     */
    public static void setContext(Context context) {
        mContext = context;
    }

    /**
     * 根据学校ID获取客服信息
     *
     * @param schoolId 学校ID
     * @param callBack 回调
     */
    public void getAdvisor(long schoolId, long brandId, BaseCallBack callBack) {
        EpaperRequest.getAdvisor(schoolId, brandId, callBack);
    }

    /**
     * 根据服务ID获取书籍
     *
     * @param schoolId  学校ID
     * @param serviceId 服务ID
     * @param page      页码
     * @param pageSize  每页条数
     * @param callBack  回调
     */
    public void getServiceBooks(long schoolId, int serviceId, int page,
                                int pageSize, BaseCallBack callBack) {
        EpaperRequest.getServiceBooks(schoolId, serviceId, page, pageSize,
                callBack);
    }

    /**
     * 根据品牌ID获取书籍
     */
    public void getEpageBookcase(int brandId, int pageIndex, int pageSize, BaseCallBack callBack) {
        EpaperRequest.getEpageBookcase(brandId, pageIndex, pageSize, callBack);
    }

    /**
     * 根据品牌ID获取书籍
     */
    public void getEpageBookcaseAll(int brandId, BaseCallBack callBack) {
        EpaperRequest.getEpageBookcaseAll(brandId, callBack);
    }

    /**
     * 根据服务ID、页码、页数获得书籍列表
     *
     * @param brandId
     * @param serviceIds
     * @param page
     * @param pageSize
     * @param callBack
     */
    public void getBookListByServiceID(int brandId, String serviceIds, int page, int pageSize,
                                       BaseCallBack callBack) {

        EpaperRequest.getBookListByServiceID(brandId, serviceIds, page, pageSize,
                callBack);
    }

    /**
     * 获取书籍目录
     *
     * @param packageId 资源包ID
     * @param cId       书籍目录ID(全部：-1)
     * @param tag       网络请求tag
     * @param callBack  回调
     */
    public void getBookCatalogue(String packageId, String cId, Object tag,
                                 BaseCallBack callBack) {
        EpaperRequest.getBookCatalogue(packageId, cId, tag, callBack);
    }

    /**
     * 获取章节资源
     *
     * @param packageId 资源包ID
     * @param cId       书籍目录ID(全部：-1)
     * @param tag       网络请求tag
     * @param callBack  回调
     */
    public void getCatalogueResourceList(String packageId, String cId, Object tag, boolean isFromDesk, int fromResource,
                                         BaseCallBack callBack) {
        EpaperRequest.getCatalogueResourceList(packageId, cId, tag, isFromDesk, fromResource, callBack);
    }


    /**
     * 学生根据考生用书ID获取布置作业章节记录
     *
     * @param brandId
     * @param serviceId
     * @param packageId
     * @param callBack
     */
    public void getReceiveBookchapters(int brandId, int serviceId, String packageId, BaseCallBack callBack) {
        EpaperRequest.getReceiveBookchapters(brandId, serviceId, packageId, callBack);
    }


    public void getAdverts(int brandId, long userId, BaseCallBack callBack) {
        EpaperRequest.getAdverts(brandId, userId, callBack);
    }

    /**
     * 获取我的作业
     *
     * @param brandId  品牌ID
     * @param page     页码
     * @param pageSize 每页数量
     * @param workType 作业完成状态 ：0所有作业，1，未完成，2，已完成
     * @param callBack 回调
     *                 isClassWork 是否是课堂作业
     */
    public void getMyWork(int brandId, int workMode, int page, int pageSize, int workType, boolean isErrorWork, boolean isClassWork,
                          BaseCallBack callBack) {
        EpaperRequest.getMyWork(brandId, workMode, page, pageSize, workType, isErrorWork, isClassWork, callBack);
    }

    /**
     * 获取我的成绩
     */
    public void getmygrade(int brandId, String moduleIds,
                           BaseCallBack callBack) {
        EpaperRequest.getmygrade(brandId, moduleIds, callBack);
    }

    /**
     * 作业通知回执
     *
     * @param workIds
     * @param callBack
     */
    public void setWorkNotifyRead(String workIds, final BaseCallBack callBack) {
        EpaperRequest.setWorkNotifyRead(workIds, callBack);
    }

    /**
     * [学生]获取章节目录信息以及下载地址
     *
     * @param packageId 资源包ID
     * @param cId       章节ID
     * @param callBack
     */
    public void getCatalogueInfo(String packageId, String cId, final BaseCallBack callBack) {
        EpaperRequest.getCatalogueInfo(packageId, cId, callBack);
    }


    public void getCatalogueInfoNew(String packageId, String cId, String moduleId, String versionId, final BaseCallBack callBack) {
        EpaperRequest.getCatalogueInfo(packageId, cId, moduleId, versionId, callBack);
    }


    public void getNewReadBookInfo(String packageId, String cId, String moduleId, String versionId, final BaseCallBack callBack) {
        EpaperRequest.getNewReadBookInfo(packageId, cId, moduleId, versionId, callBack);
    }

    /**
     * 获取单词
     *
     * @param brandId
     * @param state
     * @param word
     * @param callBack
     */
    public void getWordDetail(int brandId, String state, String word, final BaseCallBack callBack) {
        EpaperRequest.getWordDetail(brandId + "", state, word, callBack);
    }


    public void getBookOrServiceList(int brandId, int page, int pageSize, int schoolId, int gradeId,
                                     int subjectId, int salesType, String area, String keyWords, final BaseCallBack callBack) {
        EpaperRequest.getBookOrServiceList(brandId, page, pageSize, schoolId, gradeId, subjectId, salesType, area, keyWords, callBack);
    }

    public void getBookOrServiceListByType(int brandId, int applyType, int page, int pageSize, int schoolId, int gradeId, int subjectId, String area, final BaseCallBack baseCallBack) {
        EpaperRequest.getBookOrServiceListByType(brandId, applyType, page, pageSize, schoolId, gradeId, subjectId, area, baseCallBack);
    }

    public void getSubjectListByGrade(int brandId, int gradeId, int salesType, String area, int schoolId, int applyType,
                                      final BaseCallBack callBack) {
        EpaperRequest.getSubjectListByGrade(brandId, gradeId, salesType, area, schoolId, applyType, callBack);

    }

    /**
     * 提交作业答案
     *
     * @param json     答案json
     * @param callBack 回调
     */
    public void submitWork(String json, int wrokType, Answer answer, final BaseCallBack callBack) {
        submit(json, wrokType, answer.getWorkId(), answer.getContentId(), OnlineAnswerSubMitResultBean.class, callBack);
    }

    public void submitReadWork(String json, int wrokType, String workId, int contentId, final BaseCallBack callBack) {
        submit(json, wrokType, workId, contentId, SubmitResult.class, callBack);
    }

    public void submit(String json, int wrokType, final String workId, final int contentId, Class clazz, final BaseCallBack callBack) {

        EpaperRequest.submit(json, wrokType, workId, clazz, new BaseCallBack() {
            @Override
            public void success(Object data) {

               /* if (!workId.equals("0")) {//判断是否是作业
                    MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), AddPointTypes.DO_HOMEWORK, contentId + "");
                }*/
                MeDao.getInstance().getUserPoint();

                callBack.success(data);

            }

            @Override
            public void failed(int errorCode, Object data) {
                String msg = String.valueOf(data);
                switch (errorCode) {
                    case Answer.SubmitStatus.SUBMIT_WORK_NO_CLASS_ERROR:
                        msg = "未加入班级！";
                        break;
                    case Answer.SubmitStatus.SUBMIT_WORK_CARD_NOT_EXIST:
                        msg = "试卷编码不存在！";
                        break;
                }
                callBack.setUrl(getUrl());
                callBack.failed(errorCode, msg);
            }

            @Override
            public void failed(Object data) {
                callBack.setUrl(getUrl());
                callBack.failed(data);
            }
        });
    }

    public void submitDubingVideo(String json, int wrokType, final String workId, final int contentId, final BaseCallBack callBack) {

        EpaperRequest.submitDubingVideo(json, wrokType, workId, SubmitResult.class, new BaseCallBack() {
            @Override
            public void success(Object data) {
                callBack.success(data);

            }

            @Override
            public void failed(int errorCode, Object data) {
                String msg = String.valueOf(data);
                callBack.setUrl(getUrl());
                callBack.failed(errorCode, msg);
            }

            @Override
            public void failed(Object data) {
                callBack.setUrl(getUrl());
                callBack.failed(data);
            }
        });
    }

    /**
     * 更新提交过的单元测试作业
     *
     * @param doWorkId 做作业ID
     * @param callBack 回调
     */
    public void updateUnitTestWork(final String doWorkId,
                                   final BaseCallBack callBack) {
        EpaperRequest.updateUnitTestWork(doWorkId, callBack);
    }

    /**
     * 读取SD卡中资源文件
     *
     * @param path     文件路径
     * @param callBack 回调
     */
    public void getResource(final String path, final BaseCallBack callBack) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                File file = new File(path);
                if (!file.exists()) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.failed(R.string.file_no_exist);
                            }
                        }
                    });
                    return;
                }
                final StringBuffer sb = new StringBuffer();
                FileInputStream inputStream = null;
                BufferedReader br = null;
                try {
                    inputStream = new FileInputStream(file);
                    br = new BufferedReader(new UnicodeReader(inputStream,
                            Charset.defaultCharset().name()));
                    int maxBufferSize = 1 * 1024;
                    int available = inputStream.available();
                    int bufferSize = Math.min(available, maxBufferSize);
                    char[] buffer = new char[bufferSize];
                    int len = 0;
                    while ((len = br.read(buffer, 0, bufferSize)) != -1) {
                        // sb.append(EncodingUtils.getString(buffer, 0, len,
                        // "utf-8"));
                        sb.append(new String(buffer, 0, len));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.failed(R.string.error_file);
                            }
                        }
                    });
                } finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (br != null) {
                            br.close();
                        }
                    } catch (Exception e) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (callBack != null) {
                                    callBack.failed(R.string.error_file);
                                }
                            }
                        });
                        e.printStackTrace();
                    }
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        CWLog.d("debug", "a1：" + sb);
                        if (callBack != null) {
                            callBack.success(sb.toString());
                        }
                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 获取序列化本地资源
     *
     * @param type     序列化对象数组类型<br/>
     *                 方法: Type t = new TypeToken<List<自己类的名称>>(){}.getType();<br/>
     *                 or类的名称.class
     * @param callBack 回调
     */
    public void getSerializableObjects(final String path, final Type type,
                                       final BaseCallBack callBack) {
        getResource(path, new BaseCallBack() {

            @Override
            public void failed(Object data) {
                if (callBack != null) {
                    callBack.failed(data);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                if (callBack != null) {
                    callBack.failed(errorCode, data);
                }
            }

            @Override
            public void success(Object data) {
                if (callBack != null) {
                    try {
                        Gson gson = new Gson();
                        Object obj = gson.fromJson(String.valueOf(data), type);
                        callBack.success(obj);
                    } catch (JsonSyntaxException e) {

                    } catch (Exception e) {
                        e.getStackTrace();
                    }


                }
            }
        });
    }

    /**
     * 读取SD卡中资源文件
     *
     * @param path 文件路径
     */
    public String getResource(final String path) {
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        final StringBuffer sb = new StringBuffer();
        FileInputStream inputStream = null;
        BufferedReader br = null;
        try {
            inputStream = new FileInputStream(file);
            br = new BufferedReader(new UnicodeReader(inputStream,
                    Charset.defaultCharset().name()));
            int maxBufferSize = 1 * 1024;
            int available = inputStream.available();
            int bufferSize = Math.min(available, maxBufferSize);
            char[] buffer = new char[bufferSize];
            int len = 0;
            while ((len = br.read(buffer, 0, bufferSize)) != -1) {
                // sb.append(EncodingUtils.getString(buffer, 0, len,
                // "utf-8"));
                sb.append(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
            return sb.toString();
        }
    }

    /**
     * 读取本地QRCode JSON文件信息
     *
     * @param packageId 资源包ID
     * @param cId       章节ID
     * @return key拼接字段
     */
    public String getQRCodeInfo(String packageId, String cId) {
        StringBuffer sb = new StringBuffer();
        try {
            String path = ESystem.getPackagesMainJsonPath(packageId, cId);
            Gson gson = new Gson();
            Main main = gson.fromJson(getResource(path), Main.class);
            // if (main.getJsonVersion().equalsIgnoreCase(NConstants.JSON_VERSION))
            // {
            path = ESystem.getPackagesPath(mContext) + File.separator
                    + (main == null ? "" : main.getQrCodeFile());
            Type responseType = new TypeToken<List<QRCodeInfo>>() {
            }.getType();
            List<QRCodeInfo> qrCodeInfos = gson.fromJson(getResource(path),
                    responseType);
            if (qrCodeInfos != null) {
                for (QRCodeInfo qrCodeInfo : qrCodeInfos) {
                    if (qrCodeInfo.getType() == 9) {
                        sb.append(qrCodeInfo.getUrl() + ",");
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return sb.toString();
    }


    public void sentenceSubmit(String json, BaseCallBack callBack) {

    }

    /**
     * 生成json文件并打包答案（针对有泛型的workAnswerList）
     *
     * @param userId
     * @param uuid
     * @param answer
     * @param userAnswersList
     * @param responseType    Type t = new TypeToken<List<自己类的名称>>(){}.getType()
     * @param downLoadInfo
     * @param module
     * @param position
     * @param isZipAndSubmit  是否需要压缩并提交
     * @param workType        不同作业类型，接口不一样
     * @param versionId
     * @param callBack
     */
    public void packSubmitAnswer(final long userId, final String uuid,
                                 final Answer answer, final List userAnswersList, final Type responseType,
                                 final DownLoadInfo downLoadInfo, final Module module,
                                 final int position, final boolean isZipAndSubmit, final int workType, final String versionId,
                                 final BaseCallBack callBack) {

        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();

                if (null == answer) {
                    return;
                }

                answer.setJsonVersion(EConstants.JSON_VERSION);
                answer.setUserAnswer(ESystem.USER_ANSWER);
                answer.setCreateTime(System.currentTimeMillis());
                answer.setBrandId(EApplication.BRAND_ID);
                String refAnswerPath = null;
                int moduleId;

                if (module != null) {
                    ModuleContent moduleContent = module.getResourceList().get(position);
                    moduleId = module.getModuleInfo().getModuleId();

                    if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {

                        if (null != moduleContent.getRefAnswerFile() && moduleContent.getRefAnswerFile().length() > 0) {
                            refAnswerPath = ESystem.getPackagesPath(mContext)
                                    + File.separator
                                    + moduleContent.getRefAnswerFile();
                            answer.setRefAnswer(ESystem.REF_ANSWER);

                        } else {
                            //由于视频讲解跟在线作答资源没有refanser ,必须自己拷贝
                            String packageJsonPath = ESystem.getPackagesJsonPath(module.getResourceList().get(position).getResourceFile());
                            refAnswerPath = packageJsonPath;
                            answer.setRefAnswer(ESystem.REF_ANSWER);
                        }

                    }

                    answer.setResourceName(moduleContent.getResourceName());

                    if (null != versionId) {
                        //目前只有单词跟读才会走这里，因为单词跟读资源versionid 有问题
                        answer.setVersionId(versionId);
                    } else {
                        answer.setVersionId(moduleContent.getVersionId());
                    }

                    answer.setParentVersionId(moduleContent.getParentVersionId());
                    answer.setModuleId(moduleId);
                    answer.setResourceType(moduleContent.getResourceType());

                }

                if (downLoadInfo != null) {
                    answer.setPackageId(downLoadInfo.getBookId());
                    answer.setcId(downLoadInfo.getChapterId());
                }

                try {
                    // 生成main.json
                    FileUtils.save(gson.toJson(answer), ESystem.getAnswersMainPath(uuid));
                    // 生成refAnswers.json
                    if (refAnswerPath != null) {
                        File refFile = new File(ESystem.getAnswersRefAnswerPath(uuid));
                        if (!refFile.exists()) {
                            refFile.createNewFile();
                        }
                        FileUtils.copyFile(refAnswerPath, ESystem.getAnswersRefAnswerPath(uuid));
//                        FileUtils.copy(new File(refAnswerPath), ESystem.getAnswersRefAnswerPath(uuid),true);
                    }

                    // 生成userAnswer.json
                    String userAnswerJson = responseType == null
                            ? gson.toJson(userAnswersList)
                            : gson.toJson(userAnswersList, responseType);


                    FileUtils.save(userAnswerJson, ESystem.getAnswersUserAnswerPath(uuid));


                    if (!TextUtils.isEmpty(userAnswerJson)) {

                        answer.setWorkAnswers(userAnswerJson);

                    } else {
                        //转换答案出错就提示重做
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callBack.failed(R.string.read_answer_file_error);
                            }
                        });
                        return;
                    }


                    if (isZipAndSubmit) {
                        // 压缩文件
                        final String zipPath = generateZipFile(uuid);
                        //有可能压缩后包大小为零
//                        if (!TextUtils.isEmpty(zipPath) && new File(zipPath).length()>0) {
//                            answer.setDoWorkLocalPath(zipPath);
//                            //添加答案请求
//                            UploadFileHelper.getInstance().submitAnswer(answer,
//                                    userId, callBack, mHandler,workType);
//
//                        } else {
//                            mHandler.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    callBack.failed(null);
//                                }
//                            });
//                        }

                        if (!TextUtils.isEmpty(zipPath) && new File(zipPath).length() > 0) {

                            //由于存在PC端有时候解压不了Android提交的压缩包，验证是否压缩过程出了问题，
                            //目前的方法是本地对已经压缩的包先拷贝解压，如果解压成功，说明压缩包没问题
                            File file = new File(zipPath);
                            String toFilePath = ESystem.getUploadUpzipHomeworkPath() + File.separator + file.getName();
                            FileUtils.copyFile(zipPath, toFilePath);

                            ZipHelper.getInstance().addToUpZipTask(toFilePath,
                                    ESystem.getUploadUpzipHomeworkPath(), new BaseCallBack() {


                                        @Override
                                        public void success(Object data) {
                                            answer.setDoWorkLocalPath(zipPath);
                                            UploadFileHelper.getInstance().submitAnswer(answer,
                                                    userId, callBack, mHandler, workType);
                                        }

                                        @Override
                                        public void failed(Object data) {
                                            mHandler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    callBack.failed("压缩作业出错，请稍后重试");
                                                }
                                            });
                                        }

                                        @Override
                                        public void failed(int errorCode, Object data) {
                                            mHandler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    callBack.failed("压缩作业出错，请稍后重试");
                                                }
                                            });
                                        }
                                    });
                        } else {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callBack.failed(null);
                                }
                            });
                        }

                    } else { // 将记录保存在本地
                        answer.setDoWorkLocalPath(uuid);
                        //将答案记录到本地的时候会产生记录ID
                        final long saveId = StudyRecordDB
                                .insertWorkData(answer);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callBack.success(saveId);
                            }
                        });
                    }
                } catch (IOException e) {

                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.failed(R.string.error_file);
                        }
                    });
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }


    /**
     * 生成json文件并打包答案（针对有泛型的workAnswerList）
     */
    public void packSubmitAnswerTest(String json) {
        Gson gson = new Gson();
        Log.d("ciwong", "#######h5测试提交作业流程#########" + json);

        Type responseType = new TypeToken<List<VideoExplainWorkAnswers>>() {
        }.getType();


        List<VideoExplainWorkAnswers> userAnswerseList = gson.fromJson(json, responseType);

        if (userAnswerseList != null && userAnswerseList.size() > 0) {

            Log.d("ciwong", "#######userAnswerseList.size()#########" + userAnswerseList.size());
            VideoExplainWorkAnswers testObject = userAnswerseList.get(0);
            if (testObject.getLearnRecods() != null) {

                List<LearnRecord> learnRecords = testObject.getLearnRecods();

                Log.d("ciwong", "#######learnRecords.size()#########" + learnRecords.size());

                for (LearnRecord record : learnRecords) {

                    Log.d("ciwong", "#######record.getCount()#########" + record.getCount());
                    Log.d("ciwong", "#######record.getType()#########" + record.getType());
                }
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param uuid
     * @return
     */
    public String generateZipFile(String uuid) {
        // 生成zip包
        List<String> srcPaths = new ArrayList<String>();
        srcPaths.add(ESystem.getAnswersUuidPathNoCreate(uuid));
        String zipPath = srcPaths.get(0) + ".zip";
        final boolean isSuccess = ZipHelper.getInstance().addToZipTask(srcPaths,
                zipPath);
        CWLog.d("debug", "生成zip包:" + isSuccess);
        return isSuccess ? zipPath : null;
    }

    /**
     * 生成json文件并打包答案(专供提交答题卡作业使用)
     *
     * @param uuid
     * @param answer
     * @param userAnswerseList
     * @param downLoadInfo
     * @param module
     * @param position
     * @param callBack
     */
    public void packSubmitAnswer(final long userId, final String uuid,
                                 final Answer answer, final List userAnswerseList,
                                 final DownLoadInfo downLoadInfo, final Module module,
                                 final int position, final BaseCallBack callBack) {
        packSubmitAnswer(userId, uuid, answer, userAnswerseList, null,
                downLoadInfo, module, position, true, ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM, null, callBack);
    }

    /**
     * 释放资源
     */
    public void release() {
        mHandler.removeCallbacksAndMessages(null);
        instance = null;
    }

    /**
     * 添加书籍到书柜记录
     */
    public void setBookcaseToServer(int brandId, String productId, int serviceId, BaseCallBack callBack) {
        EpaperRequest.setBookcaseToServer(brandId, productId, serviceId, callBack);
    }

    /**
     * 删除书柜记录By书箱ID
     */
    public void setDelBookcaseToServer(int brandId, String productId, int serviceId, BaseCallBack callBack) {
        EpaperRequest.setDelBookcaseToServer(brandId, productId, serviceId, callBack);
    }

    /**
     * 删除书柜记录By书箱ID
     */
    public void setDelBookcaseToServerByList(int brandId, ArrayList<DeleteEP> deleteEPList, BaseCallBack callBack) {
        EpaperRequest.setDelBookcaseToServerByList(brandId, deleteEPList, callBack);
    }


    /**
     * 获取视频讲解答案
     *
     * @param callBack 回调
     */
    public void getVideoExplainAnswer(String doWorkId, int requestType,
                                      final BaseCallBack callBack) {

        if (doWorkId != null) {
//            ModuleContent moduleContent = module.getResourceList().get(position);
            EpaperRequest.getVideoExplainAnswer(doWorkId, requestType, callBack);
        }

    }

    public void getOnlineAnswer(String doWorkId,
                                final BaseCallBack callBack) {
        if (doWorkId != null) {
            EpaperRequest.getOnlineAnswer(doWorkId, callBack);
        }
    }

    /**
     * 获取zip 包更新信息
     *
     * @param callBack 回调
     */
    public void getZipPackageUpdateInfo(String appVersion,
                                        BaseCallBack callBack) {
        EpaperRequest.getZipPackageUpdateInfo(appVersion, callBack);
    }

    /**
     * 复制一个目录及其子目录、文件到另外一个目录
     *
     * @param src
     * @param dest
     * @throws IOException
     */
    private void copyFolder(File src, File dest) throws IOException {

        if (src.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdir();
            }
            String files[] = src.list();
            for (String file : files) {
                File srcFile = new File(src, file);
                File destFile = new File(dest, file);
                // 递归复制
                copyFolder(srcFile, destFile);
            }
        } else {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];

            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        }
    }

    public void getAutonomicStudyBooks(int brandId,
                                       BaseCallBack callBack) {
        EpaperRequest.getAutonomicStudyBooks(brandId, callBack);
    }

    public void getProductsbybookmark(int brandId, int bookmarkId, int gradeId, int subCategoryId, int pageIndex, int pageSize,
                                      BaseCallBack callBack) {
        EpaperRequest.getproductsbybookmark(brandId, bookmarkId, gradeId, subCategoryId, pageIndex, pageSize, callBack);
    }

    public void getInteractionList(int gradeId, int categoryId, int subCategoryId, int pageIndex, int pageSize,
                                   BaseCallBack callBack) {
        EpaperRequest.getInteractionList(gradeId, categoryId, subCategoryId, pageIndex, pageSize, callBack);
    }


    public void getStudentProductsByBookmark(int brandId, int bookmarkId, int gradeId, int pageIndex, int pageSize,
                                             BaseCallBack callBack) {
        EpaperRequest.getStudentProductsByBookmark(brandId, bookmarkId, gradeId, pageIndex, pageSize, callBack);
    }

    public void getGradeByBookmarkId(int brandId, int mBookmarkId, BaseExtCallBack callBack) {
        EpaperRequest.getGradeByBookmarkId(brandId, mBookmarkId, callBack);
    }


    public void getGradeByBookCategoryId(int typeId, BaseExtCallBack callBack) {
        EpaperRequest.getGradeByBookCategoryId(typeId, callBack);
    }

    public void getInteractionCategory(BaseExtCallBack callBack) {
        EpaperRequest.getInteractionCategory(callBack);
    }

    public void getDubbingVideoList(int gradeId, int pageIndex, int pageSize,
                                    BaseCallBack callBack) {
        EpaperRequest.getDubbingVideoList(gradeId, pageIndex, pageSize, callBack);
    }

    public void getDubVideoDetail(String versionId,
                                  BaseCallBack callBack) {
        EpaperRequest.getDubVideoDetail(versionId, callBack);
    }

    public void getDubbingVideoRecordList(int pageIndex, int pageSize,
                                          BaseCallBack callBack) {
        EpaperRequest.getDubbingVideoRecordList(pageIndex, pageSize, callBack);
    }

    public void setHeadLastBooks(String productId, int serviceId, int userId, int action,
                                 BaseCallBack callBack) {
        EpaperRequest.setHeadLastBooks(productId, serviceId, userId, action, callBack);
    }

    public void getBookDeskHomePage(int brandId, int gradeId,
                                    BaseCallBack callBack) {
        EpaperRequest.getBookDeskHomePage(brandId, gradeId, callBack);
    }

    public void getBookDeskCatalogue(String versionId,
                                     BaseCallBack callBack) {
        EpaperRequest.getBookDeskCatalogue(versionId, callBack);
    }

    /**
     * 获取评分系数
     */
    public void getScoreCoefficient(final BaseCallBack callBack) {
        EpaperRequest.getScoreCoefficient(callBack);
    }

    /**
     * 获取音标列表
     *
     * @param callBack
     */
    public void getSymbolsList(BaseCallBack callBack) {
        EpaperRequest.getSymbolsList(callBack);
    }

    public void getUserDkWorks(int brandId, int page, int pageSize, BaseExtCallBack callBack) {
        EpaperRequest.getUserDkWorks(brandId, page, pageSize, callBack);
    }

    public void getUserDkWorkDetails(String workId, BaseExtCallBack callBack) {
        EpaperRequest.getUserDkWorkDetails(workId, callBack);
    }

    public void submitDkWork(DKAnswer dkAnswer, BaseExtCallBack callBack) {
        EpaperRequest.submitDkWork(dkAnswer, callBack);
    }

    public void submitEssayWork(EssayAnswer essayAnswer, BaseExtCallBack callBack) {
        EpaperRequest.submitEssayWork(essayAnswer, callBack);
    }


    public void getSchoolList(String schoolArea, String period, String keyWords, String brandId, int page, int pagesize, BaseCallBack callBack) {
        EpaperRequest.getSchoolList(schoolArea, period, keyWords, brandId, page, pagesize, callBack);
    }

    public void getDubbingVideoRecommend(int gradeId, BaseCallBack callBack) {
        EpaperRequest.getDubbingVideoRecommend(gradeId, callBack);
    }

    public void getDubbingVideoCid(int gradeId, BaseCallBack callBack) {
        EpaperRequest.getDubbingVideoCid(gradeId, callBack);
    }

    public void getDubbingVideoListByName(int gradeId, String name, int page, int pageSize, BaseExtCallBack callBack) {
        EpaperRequest.getDubbingVideoListByName(gradeId, name, page, pageSize, callBack);
    }

    public void getDubbingVideoListBycId(String packageId, String cId, int page, int pageSize, BaseCallBack callBack) {
        EpaperRequest.getDubbingVideoListBycId(packageId, cId, page, pageSize, callBack);
    }
}
